<?php
/**
 * Created by PhpStorm.
 * Code Monkey: wcz
 * Date: 2018/3/21
 * Time: 10:19
 * PHP is the best language in the world
 */
namespace App\Service\Imessage;

use App\Models\Imessage\ChatModel;
use DB;

class MessageService
{
    /**
     * 消息列表离线消息数量
     * @param $uid
     * @return mixed
     */
    public static function getMessageList($uid)
    {
        $result = \DB::select("select b.from_uid,c.nickname,c.headimgurl,b.content,b.created_at,(select count(*) from lsj_chatlog where is_out=1 and to_uid=? and from_uid = b.from_uid) as out_nums
 from lsj_chatlog as b,lsj_user c
 where not exists(select 1 from lsj_chatlog where from_uid= b.from_uid
 and b.created_at<created_at and is_out=1 and to_uid=? ) and is_out=1 
 and b.to_uid=? and b.from_uid=c.uid",[$uid,$uid,$uid]);


        return $result;
    }

    /**
     * 获得用户离线消息详情
     */
    public static function getUserOutMessage($to_uid, $from_uid)
    {
        $result = ChatModel::select('id','to_uid','from_uid','created_at','content')
            ->where([
            'to_uid' => $to_uid,
            'from_uid' => $from_uid,
            'is_out' => 1
        ])->orderBy('id','desc')->get()->toArray();

        return $result;
    }

    /**
     * 成功获得离线消息则回调此方法
     */
    public static function changeOutMessageStatus($to_uid, $from_uid)
    {
        $result = ChatModel::where([
            'to_uid' => $to_uid,
            'from_uid' => $from_uid
        ])->update(['is_out' => 0]);

        return $result;
    }
}